package com.sword.spring.rabbitmq.b_workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.AMQP.BasicProperties;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

/**
 * com.sword.spring.rabbitmq.a_helloworld.Send
 * Created by SwordLiu on 2017-11-02.
 */
public class NewTask {

    private final static String QUEUE_NAME = "hello";

    private final static String DURABLE_QUEUE = "task_queue";

    public void send(String[] argv) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        boolean durable = true; //将消息队列标记为持久化/非持久化：持久化后，即时消息队列崩溃或退出后，消息队列仍然存在
        channel.queueDeclare(DURABLE_QUEUE, durable, false, false, null);
//        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        String message = getMessage(argv);
        BasicProperties basicProperties = MessageProperties.PERSISTENT_TEXT_PLAIN; //将消息标记为持久化消息，该消息将被保存到磁盘
        channel.basicPublish("", QUEUE_NAME, basicProperties, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");

        channel.close();
        connection.close();
    }

    private static String getMessage(String[] strings) {
        if (strings.length < 1)
            return "hello world!";
        return joinStrings(strings, " ");
    }

    private static String joinStrings(String[] strings, String delimiter) {
        int length = strings.length;
        if (length == 0) return "";
        StringBuilder words = new StringBuilder(strings[0]);
        for(int i = 1; i < length; i++) {
            words.append(delimiter).append(strings[i]);
        }
        return words.toString();
    }


    public static void main(String[] args) throws IOException, TimeoutException {
        Scanner scanner = new Scanner(System.in);
        new NewTask().send(new String[]{scanner.next()});
    }

}
